import store from '../store/index'
var websock = null
var globalCallback = null
// var socketUrl = window.location.hostname
const socketUrl = process.env.NODE_ENV === 'development' ? 'campus.hlzhjy.com:50080' : window.location.host
export default {
// 初始化websocket
  initWebSocket() {
    // ws地址 -->这里是你的请求路径
    var ws = `ws://${socketUrl}/WS/`
    if (window.WebSocket) {
      websock = new WebSocket(ws)
      websock.onmessage = (e) => {
        this.websocketonmessage(e)
      }
      websock.onclose = (e) => {
        console.log("关闭了")
        this.websocketclose(e)
      }
      websock.onopen = (e) => {
        store.dispatch('setSocketStatus', false)
        console.log(e, '连接成功')
        // this.websocketOpen(e)
      }

      // 连接发生错误的回调方法
      websock.onerror = () => {
        // setTimeout(() => {
        //   this.initWebSocket()
        // }, 2000)
        console.log('WebSocket连接发生错误')
      }
    } else {
      console.log('您当前的浏览器不支持websocket,推荐使用火狐或者谷歌浏览器')
    }
  },

  // 实际调用的方法
  sendSock(agentData, callback) {
    globalCallback = callback
    if (websock.readyState === websock.OPEN) {
    // 若是ws开启状态
      this.websocketsend(agentData)
    } else if (websock.readyState === websock.CONNECTING) {
      // 若是 正在开启状态，则等待1s后重新调用
      setTimeout(() => {
        this.sendSock(agentData, callback)
      }, 1000)
    } else {
      // 若未开启 ，则等待2s后重新调用
      setTimeout(() => {
        this.initWebSocket()
        this.sendSock(agentData, callback)
      }, 2000)
    }
  },

  // 数据接收
  websocketonmessage(e) {
    // console.log(e.data, '接收到的数据')
    window.dispatchEvent(new CustomEvent('onmessageWS', {
      detail: {
        data: JSON.parse(e.data)
      }
    }))
  },

  // 数据发送
  websocketsend(agentData) {
    websock.send(JSON.stringify(agentData))
  },

  // 关闭
  websocketclose(e) {
    store.dispatch('setSocketStatus', true)
    setTimeout(() => {
      this.initWebSocket()
    }, 5000)
    console.log('connection closed')
  },

  // 创建 websocket 连接
  websocketOpen(e) {
    store.dispatch('setSocketStatus', false)
    // window.location.reload()
    console.log('连接成功')
  }
}